<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()
const isRegister = ref(false) // 控制登录/注册表单切换

// 登录表单数据对象
const loginInfo = ref({
  account: '',
  password: '',
  agree: true
})

// 注册表单数据对象
const registerInfo = ref({
  account: '',
  password: '',
  nickname: '',
  confirmPassword: '',
  agree: true
})

// 登录表单规则
const loginRules = {
  account: [
    { required: true, message: '用户名不能为空' }
  ],
  password: [
    { required: true, message: '密码不能为空' },
    { min: 6, max: 24, message: '密码长度要求6-14个字符' }
  ],
  agree: [
    {
      validator: (rule, val, callback) => {
        return val ? callback() : new Error('请先同意协议')
      }
    }
  ]
}

// 注册表单规则
const registerRules = {
  account: [
    { required: true, message: '用户名不能为空' }
  ],
  nickname: [
    { required: true, message: '昵称不能为空' },
    { min: 2, max: 16, message: '昵称长度要求2-16个字符' }
  ],
  password: [
    { required: true, message: '密码不能为空' },
    { min: 6, max: 24, message: '密码长度要求6-14个字符' }
  ],
  
  confirmPassword: [
    { required: true, message: '请再次输入密码' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerInfo.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }
    }
  ],
  agree: [
    {
      validator: (rule, val, callback) => {
        return val ? callback() : new Error('请先同意协议')
      }
    }
  ]
}

const loginFormRef = ref(null)
const registerFormRef = ref(null)

// 登录函数
const doLogin = () => {
  const { account, password } = loginInfo.value
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      await userStore.getUserInfo({ account, password })
      ElMessage({ type: 'success', message: '登录成功' })
      router.replace({ path: '/' })
      console.log(userStore.userInfo)
    }
  })
}

// 注册函数
const doRegister = () => {
  registerFormRef.value.validate(async (valid) => {
    if (valid) {
      const { account, nickname, password } = registerInfo.value
      console.log(account, nickname, password)
      try {
        await userStore.registerUser({ account, nickname, password })
        ElMessage({ type: 'success', message: '注册成功，请登录' })
        // 注册成功后切换回登录表单
        isRegister.value = false
        // 自动填充用户名
        loginInfo.value.account = registerInfo.value.account
        // 清空注册表单
        registerInfo.value.password = ''
        registerInfo.value.confirmPassword = ''
      } catch (error) {
        ElMessage({ type: 'error', message: error.message || '注册失败' })
      }
    }
  })
}

// 切换登录/注册表单
const toggleForm = () => {
  isRegister.value = !isRegister.value
}
</script>

<template>
  <div>
    <header class="login-header">
      <div class="container m-top-20">
        <h1 class="logo">
          <RouterLink to="/">奶龙商城</RouterLink>
        </h1>
        <RouterLink class="entry" to="/">
          进入网站首页
          <i class="iconfont icon-angle-right"></i>
          <i class="iconfont icon-angle-right"></i>
        </RouterLink>
      </div>
    </header>
    <section class="login-section">
      <div class="wrapper">
        <nav>
          <a href="javascript:;" @click="isRegister = false" :class="{active: !isRegister}">账户登录</a>
          <a href="javascript:;" @click="isRegister = true" :class="{active: isRegister}">用户注册</a>
        </nav>
        <div class="account-box">
          <!-- 登录表单 -->
          <div class="form" v-if="!isRegister">
            <el-form ref="loginFormRef" :model="loginInfo" :rules="loginRules" status-icon>
              <el-form-item prop="account" label="账户">
                <el-input v-model="loginInfo.account" />
              </el-form-item>
              <el-form-item prop="password" label="密码">
                <el-input v-model="loginInfo.password" type="password" show-password />
              </el-form-item>
              <el-form-item prop="agree" label-width="22px">
                <el-checkbox v-model="loginInfo.agree" size="large">
                  我已同意隐私条款和服务条款
                </el-checkbox>
              </el-form-item>
              <el-button size="large" class="subBtn" @click="doLogin">登录</el-button>
            </el-form>
            <div class="toggle">
              还没有账号？<a href="javascript:;" @click="toggleForm">立即注册</a>
            </div>
          </div>
          
          <!-- 注册表单 -->
    <div class="form" v-else>
      <el-form ref="registerFormRef" :model="registerInfo" :rules="registerRules" status-icon>
        <el-form-item prop="account" label="账户">
          <el-input v-model="registerInfo.account" />
        </el-form-item>
        <el-form-item prop="nickname" label="昵称">
          <el-input v-model="registerInfo.nickname" />
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="registerInfo.password" type="password" show-password />
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码">
          <el-input v-model="registerInfo.confirmPassword" type="password" show-password />
        </el-form-item>
        <el-form-item prop="agree" label-width="22px">
          <el-checkbox v-model="registerInfo.agree" size="large">
            我已同意隐私条款和服务条款
          </el-checkbox>
        </el-form-item>
        <el-button size="large" class="subBtn" @click="doRegister">注册</el-button>
      </el-form>
      <div class="toggle">
        已有账号？<a href="javascript:;" @click="toggleForm">立即登录</a>
      </div>
    </div>
  </div>
</div>
    </section>

    <footer class="login-footer">
      <div class="container">
        <p>
          <a href="javascript:;">关于我们</a>
          <a href="javascript:;">帮助中心</a>
          <a href="javascript:;">售后服务</a>
          <a href="javascript:;">配送与验收</a>
          <a href="javascript:;">商务合作</a>
          <a href="javascript:;">搜索推荐</a>
          <a href="javascript:;">友情链接</a>
        </p>
        <p>CopyRight © 奶龙商城</p>
      </div>
    </footer>
  </div>
</template>

<style scoped lang='scss'>
.login-header {
  background: #fff;
  border-bottom: 1px solid #e4e4e4;

  .container {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
  }

  .logo {
    width: 200px;

    a {
      display: block;
      height: 132px;
      width: 100%;
      text-indent: -9999px;
      background: url("@/assets/images/logo.png") no-repeat center 18px / contain;
    }
  }

  .sub {
    flex: 1;
    font-size: 24px;
    font-weight: normal;
    margin-bottom: 38px;
    margin-left: 20px;
    color: #666;
  }

  .entry {
    width: 120px;
    margin-bottom: 38px;
    font-size: 16px;

    i {
      font-size: 14px;
      color: $xtxColor;
      letter-spacing: -5px;
    }
  }
}

.login-section {
  background: url('@/assets/images/login-bg.png') no-repeat center / cover;
  height: 488px;
  position: relative;

  .wrapper {
    width: 380px;
    background: #fff;
    position: absolute;
    left: 50%;
    top: 54px;
    transform: translate3d(100px, 0, 0);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.15);

    nav {
      font-size: 14px;
      height: 55px;
      margin-bottom: 20px;
      border-bottom: 1px solid #f5f5f5;
      display: flex;
      padding: 0 40px;
      text-align: right;
      align-items: center;

      a {
        flex: 1;
        line-height: 1;
        display: inline-block;
        font-size: 18px;
        position: relative;
        text-align: center;
        color: #666;
        
        &.active {
          color: $xtxColor;
          font-weight: bold;
        }
        
        &:not(:last-child) {
          border-right: 1px solid #f5f5f5;
        }
      }
    }
  }
}

.login-footer {
  padding: 30px 0 50px;
  background: #fff;

  p {
    text-align: center;
    color: #999;
    padding-top: 20px;

    a {
      line-height: 1;
      padding: 0 10px;
      color: #999;
      display: inline-block;

      ~a {
        border-left: 1px solid #ccc;
      }
    }
  }
}

.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: center;
    font-size: 14px;
    color: #666;

    a {
      color: $xtxColor;
      margin-left: 5px;

      &:hover {
        text-decoration: underline;
      }
    }
  }

  .form {
    padding: 0 20px 20px 20px;

    &-item {
      margin-bottom: 28px;

      .input {
        position: relative;
        height: 36px;

        >i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }

        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;

          &.error {
            border-color: $priceColor;
          }

          &.active,
          &:focus {
            border-color: $xtxColor;
          }
        }

        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }

      >.error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: $priceColor;

        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }

    .agree {
      a {
        color: #069;
      }
    }

    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: $xtxColor;

      &.disabled {
        background: #cfcdcd;
      }
    }
  }

  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}

.subBtn {
  background: $xtxColor;
  width: 100%;
  color: #fff;
}
</style>